import { Rules } from "async-validator";
import { createHash } from "crypto";
import { Context } from "koa";
import paginate from "../utils/paginate";
import response from "../utils/response";
import validate from "../utils/validate";
import AdminService from "../service/AdminService";

class AdminController {
  async getAdminList(ctx: Context) {
    const usp = new URLSearchParams(ctx.querystring)
    // console.log(usp.get('page'), usp.get('pageSize'))
    let page = 1, pageSize = 10;
    // 进行类型转换的时候一定要判断一下能否转化为数字，保证程序的健壮性
    if (usp.get('page') !== null && !isNaN(Number(usp.get('page')))) {
      page = Number(usp.get('page'))
    }
    if (usp.get('pageSize') !== null && !isNaN(Number(usp.get('pageSize')))) {
      pageSize = Number(usp.get('pageSize'))
    }
    const { rows, count } = await AdminService.getAdminListByPage(page, pageSize)
    response.success(ctx, paginate(rows, page, pageSize, count))
  }
  async addAdmin(ctx: Context) {
    const rules: Rules = {
      name: [
        {
          type: 'string',
          required: true,
          message: '用户名不能为空'
        }
      ],
      password: [
        {
          type: 'string',
          required: true,
          message: '密码不能为空'
        }, {
          type: 'string',
          min: 6,
          max: 20,
          message: '密码长度6-20位'
        }
      ]
    }
    interface IAdmin {
      id: number,
      name: string,
      password: string
    }
    const { data, error } = await validate<IAdmin>(ctx, rules)
    if (error !== null) {
      return response.error(ctx, {}, error)
    }
    // 判断是否存在 该管理员
    const adminName = await AdminService.getAdminByName(data.name)
    if (adminName !== null) {
      return response.error(ctx, '', '管理员已存在')
    }

    data.password = createHash('md5').update(data.password).digest('hex'); // 密码加密
    // console.log('密码：', data.password)
    try {
      const row = await AdminService.addAdmin(data)
      // console.log(row)
      if (row.id > 0) {
        return response.success(ctx)
      }
      return response.error(ctx, '', '插入失败')
    } catch (error) {
      console.log(error)
      return response.error(ctx, '', 'sql异常')
    }
  }
  async updateAdmin(ctx: Context) {
    const id = ctx.params['id'] as number
    const admin = await AdminService.getAdminById(id)
    if (admin === null) {
      return response.error(ctx, '', '管理员不存在')
    }
    const rules: Rules = {
      name: [{
        type: 'string',
        required: true,
        message: '用户名不能为空'
      }]
    }
    interface IAdmin {
      name: string,
      password: string,
      mobile: string,
      email: string,
    }
    const { data, error } = await validate<IAdmin>(ctx, rules)
    if (error !== null) {
      return response.error(ctx, '', error)
    }
    if (data.password !== undefined && data.password !== '') {
      data.password = createHash('md5').update(data.password).digest('hex'); // 密码加密
    }
    console.log(id, data)
    try {
      const [number] = await AdminService.updateAdmin(id, data)
      if (number > 0) {
        return response.success(ctx)
      } else {
        return response.error(ctx, '', '更新失败')
      }
    } catch (error) {
      console.log(error)
      return response.error(ctx, '', 'sql异常')
    }
  }
  async deleteAdmin(ctx: Context) {
    const id = ctx.params['id'] as number
    const admin = await AdminService.getAdminById(id)
    if (admin === null) {
      return response.error(ctx, '', '管理员不存在')
    }
    // const [number] = await AdminService.deleteAdmin(id)
    // if (number > 0) {
    //   return response.success(ctx)
    // }
    const number = await AdminService.deleteAdmin(id)
    if (number > 0) {
      return response.success(ctx)
    }
    return response.error(ctx, '', '删除失败')
  }
}

export default new AdminController
